/*
 * @Description: 
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-10-14 20:04:32
 * @LastEditTime: 2022-08-10 09:16:06
 * @FilePath: \cscec-pms-admin\src\utils\service.js
 */
import axios from 'axios'
import store from '../store'
import notification from 'ant-design-vue/es/notification'

import { codeHeaders, encryptBody } from '@/tool/sm.js'
// 创建axios实例
const service = axios.create({
  baseURL: '/api',
  timeout: 60 * 5 * 1000,
  withCredentials: true
})
// request拦截器
service.interceptors.request.use((config) => {
  // 如果没有设置Content-Type，默认application/json
  if (!config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/json'
  }
  // 方法做防重返和防篡改
  // if (process.env.VUE_APP_ENCRYPTION === '1') {
  config = codeHeaders(config)
  config = encryptBody(config)
  // }
  // 每次发送请求之前判断vuex中是否存在token
  // 如果存在，则统一在http请求的header都加上token
  const token = window.localStorage.getItem('access_token')
  console.log(token)
  if (token) {
    config.headers.Authorization = 'Bearer ' + JSON.parse(token)
  }
  return config
},
  (error) => {
    Promise.reject(error)
  })
const accessError = e => {
  const data = (e.response && e.response.data) || {}
  //无效令牌
  if (parseInt(data.status) === 401) {
    store.dispatch('SetHasRouters', false)
    // 退出登录
    // Vue.getAcloudProvider().logout()
  } else {
    notification.error({
      message: '提示',
      description: data.message || data.error_description || '发生异常了，请稍后重试！'
    })
  }
}
// respone拦截器
service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const code = error?.response?.data?.code
    console.log(error)
    // 4004：需要修改密码
    const whiteList = ['4004']
    if (whiteList.includes(code)) {
      accessError(error)
    } else {
      const data = (error.response && error.response.data) || {}
      notification.error({
        message: '提示',
        description: data.message || data.error_description || '发生异常了，请稍后重试！'
      })
    }
    return Promise.reject(error)
  }
)
export default service
